# -*- coding: utf-8 -*-
# --------------------------------------
# @Time    : 2025/6/19 22:32
# @File    : book_list.py
# @Project : Practice_flask_0619
# @Author  : CHH
# @Desc    : Windows   文件描述
# @Copyright : © 2025 HORDOR . All rights reserved.
# @Version : 1.0.0 20250628
# --------------------------------------

from flask import Blueprint, session, redirect, render_template, request
import functools
from utils import db
import xlrd

od_bp = Blueprint('order', __name__)



def auth(func):  # 认证装饰器
    @functools.wraps(func)  # 使得装饰器返回原函数名名
    def decorated(*args, **kwargs):
        if session.get("user_info"):
            return func(*args, **kwargs)
        return redirect("/login")

    return decorated


@od_bp.route('/')
@od_bp.route('/index')
@auth
def index():
    book_list = db.fetch_all("select * from `book` ", [])
    return render_template("index.html", book_list=book_list)


@od_bp.route('/upload', methods=["GET", "POST"])
def upload():
    if 'excel_file' not in request.files:
        return "没有选择文件", 400

    file = request.files['excel_file']
    print(file)
    print(file.filename)
    if file.filename == '':
        return "没有选择文件", 400

    if file:
        if '.' in file.filename and \
               file.filename.rsplit('.', 1)[1].lower() in {'xls', 'xlsx'}:
            try:
                # 直接处理上传的文件内容
                file_data = file.read()
                workbook = xlrd.open_workbook(file_contents=file_data)
                sheet = workbook.sheet_by_index(0)

                for row_idx in range(1, sheet.nrows):
                    row_data = sheet.row_values(row_idx)
                    print(row_data)
                    author = row_data[2]
                    title = row_data[0]
                    price = row_data[1]
                    db.insert_one(
                        "INSERT INTO `book` (author, title, price, author_id) VALUES (%s, %s, %s, 2)",
                        (author, title, price)
                    )

                return redirect("/index")
            except Exception as e:
                return f"处理失败: {str(e)}", 500
        else:
            return "无效的文件类型，须xls文件", 400
    else:
        return "无效的文件类型，须xls文件", 400



